<template>
  <div>
    <el-button type="success" round @click="handleAddAdministrators"
      >+ 新增管理员</el-button
    >
    <el-button type="primary" round @click="handleAddVisitor"
      >+ 新增游客</el-button
    >
    <el-dialog
      :title="tips"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="name">
          <el-input
            v-model.trim="ruleForm.name"
            autocomplete="off"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model.trim="ruleForm.pass"
            autocomplete="off"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            type="password"
            v-model.trim="ruleForm.checkPass"
            autocomplete="off"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit()" class="submit"
            >确定</el-button
          >
          <el-button type="info" @click="resetForm('ruleForm')" class="reset"
            >重置</el-button
          >
          <el-button @click="cancel" class="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      :row-class-name="tableRowClassName"
      height="90%"
    >
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column prop="password" label="密码"> </el-table-column>
      <el-table-column prop="limit" label="权限"> </el-table-column>
      <el-table-column prop="type" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.type"
            :active-text="scope.row.type ? '启用中' : '已停用'"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="limit" label="操作">
        <template slot-scope="scope"
          ><el-button
            icon="el-icon-edit"
            plain
            circle
            @click="handleEdit(scope.row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handleDelete(scope.row)"
          ></el-button
        ></template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { List } from "../api/mockServeData/account.js";
import { delAccount, editAccount, addAccount } from "../api";
export default {
  methods: {
    // 表单关闭的时候
    handleClose() {
      this.resetForm("ruleForm");
      this.dialogVisible = false;
    },
    submit() {
      this.submitForm("ruleForm");
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 后续对表单数据的处理
          if (this.modallType === 0) {
            this.ruleForm.id++;
            addAccount(this.ruleForm).then(() => {
              // 重新获取列表的接口
              this.tableData = List;
            });
          } else if (this.modallType === 1) {
            editAccount(this.ruleForm).then(() => {
              // 重新获取列表的接口
              this.tableData = List;
            });
          }
          // 清空表单数据
          this.resetForm("ruleForm");
          // 关闭弹窗
          this.dialogVisible = false;
        }
      });
    },
    handleEdit(row) {
      this.modallType = 1;
      this.dialogVisible = true;
      // 需要对当前行数据进行深拷贝
      this.ruleForm = {
        pass: row.password,
        checkPass: row.password,
        name: row.username,
        id: row.id,
        limit: row.limit,
      };
    },
    handleAddAdministrators() {
      this.ruleForm = {
        pass: "",
        checkPass: "",
        name: "",
        id: this.ruleForm.id,
        buttonType: 0,
        limit: this.ruleForm.limit,
      };
      this.modallType = 0;
      this.dialogVisible = true;
    },
    handleAddVisitor() {
      this.ruleForm = {
        pass: "",
        checkPass: "",
        name: "",
        id: this.ruleForm.id,
        buttonType: 1,
        limit: this.ruleForm.limit,
      };
      this.modallType = 0;
      this.dialogVisible = true;
    },
    cancel() {
      this.handleClose();
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          return true;
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.ruleForm = {
        pass: "",
        checkPass: "",
        name: "",
        id: this.ruleForm.id,
        buttonType: this.ruleForm.buttonType === 0 ? 0 : 1,
        limit:
          this.modallType === 0
            ? this.ruleForm.buttonType === 0
              ? "管理员"
              : "游客"
            : this.ruleForm.limit,
      };
      this.$refs[formName].resetFields();
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 0) {
        return "warning-row";
      }
      return "";
    },
    handleDelete(row) {
      this.$confirm("此操作将会销毁该账号，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delAccount({ username: row.username }).then(() => {
            this.$message({
              type: "success",
              message: "销毁成功!",
            });
            // 获取的列表数据
            this.tableData = List;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "销毁失败",
          });
        });
    },
  },
  data() {
    var checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      for (let i = 0; i < List.length; i++) {
        console.log(List[i].id, this.ruleForm.id);
        if (
          (List[i].id !== this.ruleForm.id &&
            value === List[i].username &&
            this.modallType === 1) ||
          (value === List[i].username && this.modallType === 0)||value==='username'
        ) {
          return callback(new Error("这个用户名被使用咯"));
        }
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      ruleForm: {
        id: "2",
        pass: "",
        checkPass: "",
        name: "",
        buttonType: 1,
        limit: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        name: [{ validator: checkName, trigger: "blur" }],
      },
      modallType: 0,
      tableData: [],
    };
  },
  mounted() {
    this.tableData = List;
  },
  computed: {
    tips() {
      if (this.modallType === 0) {
        if (this.ruleForm.buttonType === 0) {
          return "新增管理员";
        } else {
          return "新增游客";
        }
      } else {
        return this.ruleForm.limit;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.el-table--border {
  margin-top: 15px;
}
/deep/button.el-button.cancel.el-button--default {
  float: right;
  margin: 20% 5px 20px 0;
}
/deep/button.el-button.reset.el-button--info {
  float: right;
  margin: 20% 5px 20px 0;
}
/deep/.el-input__inner {
  width: 100%;
}
/deep/.el-dialog__body {
  padding: 70px 20px 0 10px;
}
/deep/button.el-button.submit.el-button--primary {
  float: right;
  margin: 20% 0 20px 0;
}
.el-input {
  width: 85%;
}
</style>